package com.hnu.model;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.hnu.util.PageInfoBean;

/**
 	* A data access object (DAO) providing persistence and search support for Userbookmark entities.
 			* Transaction control of the save(), update() and delete() operations 
		can directly support Spring container-managed transactions or they can be augmented	to handle user-managed Spring transactions. 
		Each of these methods provides additional information for how to configure it for the desired type of transaction control. 	
	 * @see com.hnu.model.Userbookmark
  * @author MyEclipse Persistence Tools 
 */

public class UserbookmarkDAO extends HibernateDaoSupport  {
	     private static final Logger log = LoggerFactory.getLogger(UserbookmarkDAO.class);
		//property constants
	public static final String BOOKMARK_TITLE = "bookmarkTitle";
	public static final String BOOKMARK_DESC = "bookmarkDesc";
	public static final String BOOKMARK_URL = "bookmarkUrl";
	public static final String ENTER_TIME = "enterTime";
	public static final String FLAGS = "flags";



	protected void initDao() {
		//do nothing
	}
	
	/*********************�ֹ���� start******************************/
	
	public boolean isCanModify(long userbookmarkId,long userId)
	{
		String hql = "SELECT count(*) FROM Userbookmark as userbookmark WHERE userbookmark.userBookmarkId = ? AND userbookmark.user.userId = ?";
		int allCount = ((Long) (this.getHibernateTemplate()
				.find(hql, userbookmarkId, userId)
				.iterator().next())).intValue();
		boolean result = false;
		if(allCount > 0)
		{
			result = true;
		}
		return result;
	}
	public int getUserBookmarkCountByTwo(long userId, long bookmarkId)
	{
		String hql = "SELECT count(*) FROM Userbookmark as userbookmark WHERE userbookmark.user.userId = ? AND userbookmark.bookmark.bookmarkId = ?";
		int allCount = ((Long) (this.getHibernateTemplate()
				.find(hql, userId, bookmarkId)
				.iterator().next())).intValue();
		return allCount;
	}
	
	public int getUserBookmarkCountByUserId(long userId) {
		String hql = "SELECT count(*) FROM Userbookmark as userbookmark WHERE userbookmark.user.userId = ?";
		int allCount = ((Long) (this.getHibernateTemplate()
				.find(hql, userId)
				.iterator().next())).intValue();
		return allCount;
	}

	public PageInfoBean getUserBookmarkByUserId(final long userId, final int pageSize,
			final int pageIndex) {
		PageInfoBean result = new PageInfoBean();
		Object dataList = this.getHibernateTemplate().executeFind(
				new HibernateCallback() {

					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						String hql = "FROM Userbookmark as userbookmark WHERE userbookmark.user.userId = ? ORDER BY userbookmark.userBookmarkId desc";
						Query q = session.createQuery(hql);
						q.setParameter(0, userId);
						int firstResultIndex = pageSize * (pageIndex - 1);
						q.setFirstResult(firstResultIndex);
						q.setMaxResults(pageSize);
						return q.list();
					}
				});
		result.setDataList(dataList);
		result.setCurrentPageNum(pageIndex);
		result.setPageSize(pageSize);
		return result;
	}
	
	/*********************�ֹ���� end******************************/
    
    public void save(Userbookmark transientInstance) {
        log.debug("saving Userbookmark instance");
        try {
            getHibernateTemplate().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }
    
	public void delete(Userbookmark persistentInstance) {
        log.debug("deleting Userbookmark instance");
        try {
            getHibernateTemplate().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }
    
    public Userbookmark findById( java.lang.Long id) {
        log.debug("getting Userbookmark instance with id: " + id);
        try {
            Userbookmark instance = (Userbookmark) getHibernateTemplate()
                    .get("com.hnu.model.Userbookmark", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    
    public List findByExample(Userbookmark instance) {
        log.debug("finding Userbookmark instance by example");
        try {
            List results = getHibernateTemplate().findByExample(instance);
            log.debug("find by example successful, result size: " + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }    
    
    public List findByProperty(String propertyName, Object value) {
      log.debug("finding Userbookmark instance with property: " + propertyName
            + ", value: " + value);
      try {
         String queryString = "from Userbookmark as model where model." 
         						+ propertyName + "= ?";
		 return getHibernateTemplate().find(queryString, value);
      } catch (RuntimeException re) {
         log.error("find by property name failed", re);
         throw re;
      }
	}

	public List findByBookmarkTitle(Object bookmarkTitle
	) {
		return findByProperty(BOOKMARK_TITLE, bookmarkTitle
		);
	}
	
	public List findByBookmarkDesc(Object bookmarkDesc
	) {
		return findByProperty(BOOKMARK_DESC, bookmarkDesc
		);
	}
	
	public List findByBookmarkUrl(Object bookmarkUrl
	) {
		return findByProperty(BOOKMARK_URL, bookmarkUrl
		);
	}
	
	public List findByEnterTime(Object enterTime
	) {
		return findByProperty(ENTER_TIME, enterTime
		);
	}
	
	public List findByFlags(Object flags
	) {
		return findByProperty(FLAGS, flags
		);
	}
	

	public List findAll() {
		log.debug("finding all Userbookmark instances");
		try {
			String queryString = "from Userbookmark";
		 	return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
    public Userbookmark merge(Userbookmark detachedInstance) {
        log.debug("merging Userbookmark instance");
        try {
            Userbookmark result = (Userbookmark) getHibernateTemplate()
                    .merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(Userbookmark instance) {
        log.debug("attaching dirty Userbookmark instance");
        try {
            getHibernateTemplate().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
    
    public void attachClean(Userbookmark instance) {
        log.debug("attaching clean Userbookmark instance");
        try {
            getHibernateTemplate().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

	public static UserbookmarkDAO getFromApplicationContext(ApplicationContext ctx) {
    	return (UserbookmarkDAO) ctx.getBean("UserbookmarkDAO");
	}
}